var fs = require('fs');
const sd = require('silly-datetime');
var phantom = require('phantom');
var express = require('express');

var app = express();

function getDateTime() {
    return sd.format(new Date(), 'YYYYMMDD_HHmmss')
}

app.get('/genImage/:url', async function (req, res) {
    //1.定义图片路径
    let reqUrl = req.params.url;
    let imageName = './' + getDateTime() + '_' + new Date().getMilliseconds() + '.png';
    let success_flag = false;

    console.log(getDateTime() + ' ' + '目标地址: ' + req.params.url + ' 临时文件名: ' + imageName)

    try {
        //2.执行截图
        phantom.create().then(function (ph) {
            ph.createPage().then(function (page) {
                page.open(reqUrl).then(function (status) {
                    if (status === 'success') {
                        // 等待2秒，确保页面加载完成
                        setTimeout(function () {
                            // 截图并保存为example.png
                            page.render(imageName).then(function () {
                                console.log(getDateTime() + ' ' + '截图已保存: ' + imageName);
                                success_flag = true;

                                //关闭页面
                                page.close();
                            });
                        }, 500);
                    } else {
                        console.log('无法打开网页' + reqUrl);
                        //关闭页面
                        page.close();
                    }
                });
            });
        });

        //3.线程等待---最多等待60s
        count = 0;
        while (count < 200 && !success_flag) {
            count++;
            await new Promise(resolve => setTimeout(resolve, 300));
        }

        //4.读取文件
        var responseData = [];//存储文件流
        var stream = fs.createReadStream(imageName);
        if (stream) {//判断状态
            stream.on('data', function (chunk) {
                responseData.push(chunk);
            });

            stream.on('end', function () {
                res.set('Content-Type', 'image/png');
                res.write(Buffer.concat(responseData));
                res.end();
            });
        }
    } catch (e) {
        console.log(getDateTime() + ' ' + '执行异常: ' + imageName);
        console.log(e);
    } finally {
        //5.删除文件
        fs.unlink(imageName, (err) => {
            if (err) throw err;
            console.log(getDateTime() + ' ' + '文件已删除: ' + imageName);
        });
    }
})

var server = app.listen(9053, function () {
    console.log('服务运行在http://0.0.0.0:9053/genImage/urlEncode地址')
})
